package com.foucus.myfouces.Resource.Util;

import android.util.Base64;
import android.util.Log;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

/**
 * @author alun (http://alunblog.duapp.com)
 * @version 1.0
 * @created 2013-5-17
 */
public class Rsa {
    private static final String RSA_PUBLICE =
            "MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAsRwOpbpqxaBxO7Uj+rg9" +
                    "t1QZAGy5+b2TTy5hLYTmgjmfNzFEyrBGPUl/CceVUnlOG8YWMSjacBQ/v7+2DQW6" +
                    "Gmp8vVaMTsVHuMA3nM1DORuKqSrBTdpOLfQ1zdQHCTO4RggsSlyLKPBxK2WE1kQX" +
                    "+x060EapBIMj0VXHFzDGmW7lzrOFf47CBNFnwPzcDNvKnuqvQiv62fb++HTkB6B2" +
                    "FOjeNw5K0KZYIKoATXdxIMLyw8169nyLtehKeCrlbVv/xFdKcotx8FjJPRdTr30W" +
                    "l+EEK2oSIpnGYfj7wf25G6askg0cc3Eks/nmaRdFIDPfF6gd6mWioZjj22MGYiQ2" +
                    "lLWNhoh+J2ZRPouwREC+ZHpS1ncyFFE+If5jnUeMrzXjjI0Fb8Bjyc39PYpi+eeX" +
                    "leWm4NDKmEsLxuKAsIS94ykR392munXVZhh7oC/1cQ/buFowFOfwqnhLnBZGMwyQ" +
                    "6LLZQbKJl84jPOMy76nP0DEBvR60hz6MB1M4qLt8PxjvHJ9xf4WMxwe9fDqMevo+" +
                    "J9nbgE0l3rA2G8dWxMzrLyN2miWDI1unaUreXBqk+L9Q9ljGsl3PdLFa08JWSwI2" +
                    "o6qqL4vUtUMdF3trz/2niuMYAM+7S2E9ZST0Q1cgWfyjY/rjbTAyjpTZiJDg5bT0" +
                    "7jT7iPEUjLBzlh7JaFR958cCAwEAAQ==";

    private static final String RSA_PRIVATE =
            "Proc-Type: 4,ENCRYPTED" +
                    "DEK-Info: AES-EDE3-CBC,1C2397A3978918F0"+
                    "ZfRZe+qTJbvS4h2eqBkhuZQ17gQRD7yUjfbDM7Y/iRNIh3jjytO15js+/fvEF0qH" +
                    "rlrU+ByK5aqSA3rHxZ4MrxAiDuHdjWdowlx1ab/aGWP+ZGZBHsF5HiXCWFUfNshT" +
                    "cnQ9UwEmzFIPZecEUyFB2owge57BGKyHUSKa1UmYpMSgbkbnuStSXp4HJGhQmLKE" +
                    "iFbGY4TZbIdUZnhUHQShtMEaY9+nIL8GpjhDsN1B6yOFqnobW6XearU7meEGyYUn" +
                    "RK2LqdaWVEw80eqyOH3mfPnzJLeNjRQoIh5wCdJlFPW4YkF3KgRGUKHA6pw06bmn" +
                    "R7Mu8pQNOxErBFqNZadINdkeocRQtObMJdqkaFhs0VLN+ig4HZBWK+iSy6m9qUMT" +
                    "DgSkmotRcDQaMl/GNjPnoQFriNoMtAUSZ8Hkt8i/PIMQY9Puv9u1zgB/WzAOr0WD" +
                    "bK7fSUGHkGhp/hevBNYiitGzy1lSLqcXdEfUlw/B6EF0fp5ChuCM+G/pA74GVqnC" +
                    "GXVv8IKxr9PISOyu96eaHfJEQsp5u1y5SVmFJmaL/KOxeFdmiOE0ApjtHtyaTrJU" +
                    "NbIaBVulD/TVMLqs8dE8y64b/3x0Ewb5sGsDRQQXAgX+53S12aNlXKq/tImfa4rt" +
                    "J16uIMJqSy1fz/kfkCTm7VsRg62qHRoL55i3TzThP99TOCkdGINpH2du41qEK/yh" +
                    "PmJshGsF8lvojrpMKF5U84FOrQBC3TSnOgLEji9TppQIvEuaUnMAIgy5f3EuuQEw" +
                    "lW4+Yvz7+xZ8V3pw59fmawSq7mFqe00MCjFFnfdO3HSb07sUiQ0WpaOPYF7oCtmi" +
                    "FYlDuqmdkVqQa4Lojy67a01Wy3sFMvc2ZpW7mxrEccjpoWj/kihhnJUhpMZ1Ln4X" +
                    "fTMg1pzY64eJ1Ajlwof0eK9E9fUIiEmbr+qpgAfqc/fKpNVFnIIIvJf3PbfRtGgd" +
                    "5KmewQyVw6TYEoq6lusLXiuyJkx6yTiSExHxF/M+fCO4fCIw2plqMgmTwdMWvVX8" +
                    "AeAdAO6JfRtrjMAiFNirCkD3cnodk0OHf9fe48T1R8bSGutw7sP85y4b7ct8Qu9/" +
                    "1okNl8aIlE2ycYfBjlvkT6Jq1Lye0e+Y4+fNIBMVnhrmOZ1avZCrkRWlV0otJlIx" +
                    "v6cIO9ARvqF4kM9bjSjoon7YmFnOj6fJtSs8r7EnnRp3RdE7w7TCBkhPSiXm1OCb" +
                    "QSbpQd87VMRf2CPorcNP1YMRiAXhhFRKSZcmVES0y3tAyoTG6tbhnPNbSdSsltdi" +
                    "mPH3oInPvC81AtpS0sdqGv3mRmDZBOG9semSpGRolWSL5Pnds0yG4UqtTfy/QwJX" +
                    "xQ3BIz8tMBTuLDOP/1eohcy9h6HwTCd8ngvhNIHnah01AL4S9qKsijJYRmxAImTf" +
                    "CkFESSBdN8vENoO8M+Lr3VPctxJ+tjgbfAUsB8h+PQ3rUhoSYa5JfUH3km+44heU" +
                    "pjrRh+j/DmtIXLdDtXK4oqnGvhZG3XID2UW/MXikc872VVek7jpRLad36nb4z4+2" +
                    "J+Qg4LCRKlgLKLy79GnUDHzTIgPdUKoln+xR6s9x+gjU83MCCW0cn11z9VCU1Uaj" +
                    "cQ2WqHIleFAmr+n1JZ5YMVdEeak9usgOlvTwzO2+ilFhqAgGVIQ7DhtxYMpHE9VW" +
                    "crrs5WitWIxI5Y8weTyFLSLW3/g6965+7qXGwwKPKroRFJ9jIk8klDq9eC6usj0m" +
                    "WxWSRaRt9+i8lN8ATlTJgmXs8Io2d57N5cMqo9nZJWCfJ3JvJNenZ7/fVcuAK9h6" +
                    "QVz6OEae96Vw0rZEvsNY5m51+GQO58HWm9GuIJd8b9y/bP+jOGZyaaSfFgDZfPkc" +
                    "r+nJ18TIC2cgOY4lfCWGO+ylGrqDumIwIeXPcxb7jBuea45eHQlnax4WgX7zwCdQ" +
                    "lLo9TiyOyzn21kYt6kdiPH7tNmH7hxGPhXD8Rw5vvXCewgD7WAvoaCQi0p0bMgEp" +
                    "L4QftbNcjj2ENgMtlCBQ+iIGtKkbiRkLXBwAuK8x/xD4gcNh50e+j5xAj2oDguCh" +
                    "4nHQf0YNtOMS5VZFWaxzN7A06G38ntkrEKyguS0NxAXXNIgkyUUDE5MHBmrleWyH" +
                    "iAZKbq0oiqrQbDIvQsTTH5lnNxDZxPO+VRXCXIZMUBflXLORkVOC2fwm+xRoMLDU" +
                    "wx25y6xUKZXNiCAT5snuTpO1n/rGiwrXsHiPDXyVoLuGIfldk2am2QC4ZaJ/+Suz" +
                    "TiDTL3MN1D3e/9UnJGwI+fxPtZF5fe7d78P8U7FuxJYdn2OKzQebNM1WhvkBJdem" +
                    "fz63WRI4OUoZ8na3eG4G4gDOWD3YTtX08FPQIUxJHTUTMAVhOl8B/z1mLNO/4ODE" +
                    "neAhHXAX2tfxkx+/8eL486TMAsro/P61WBFgFALkEeycdZyG6rJ/Cg6z1PgWTia3" +
                    "y57ulSP+sgmcne+HNSuNEci8PDl2/HZAwR1OdjPWliCFPOibBsUeEbrll2cP+TmN" +
                    "sb7Ki2jtVlKsS5/NKIqWXQTeDLAQqEjAiIt+0tYuB+vkKjM25VImGnAMiTefI/Oy" +
                    "PoR+/4ZG2wmB2JIKXrks928vO48HXhP5T32PlMvXFT358SfdDwsCof2JmCu0Uj47" +
                    "wJ8PzbCZUIH5XmBlmdGYDS+qhIM8PSriiOwq0ABLko+JrffB1yv0DjINNXuU9SDd" +
                    "VvsATT187B6LfjbYlIpqXclaRq9nPTIYsMuVwIElYTl/a0Ph79KjTmnuhnVdogEk" +
                    "nces8U2uV5fzVFZVs41IniUUng4wJzi7lsqD4h5IRQxnEUl4iaTfSnA4Yj7nV0FO" +
                    "l3UKwqEE0ryKKm+HcgCiHIFKR5y5BYaKhcyI1WfrIpha0YB8vVYvlW3zzLIgTjFG" +
                    "nwdHFINrSWWA1Z9wbAWXashXRRgQi1sfPxO5jQsJgRYXhRvZB+qX6tqZI7f3r5Qf" +
                    "6XxY3T/F0XGS/g/W2hMhJpxWRk1MdVxrfyCKgRQ/tmlQoW0Vg5N+42Abgy1MzAKC" +
                    "FSHIXPrSrw/OT0mTtCAY75cVgZf6vjb5EsNicV8052ZcETTInOhjGb1C94Cg2gHO" +
                    "qAtEutRHp2jqTvjVb3CfBQLqNAYny1xT1RjuHW6l43JJwbPUkYQGLQCvAK8vZyrC";


    private static final String ALGORITHM = "RSA";

    /**
     * 得到公钥
     *
     * @param algorithm
     * @param bysKey
     * @return
     */
    private static PublicKey getPublicKeyFromX509(String algorithm,
                                                  String bysKey) throws NoSuchAlgorithmException, Exception {
        byte[] decodedKey = Base64.decode(bysKey, Base64.DEFAULT);
        X509EncodedKeySpec x509 = new X509EncodedKeySpec(decodedKey);

        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        return keyFactory.generatePublic(x509);
    }

    /**
     * 使用公钥加密
     *
     * @param content
     * @return
     */
    public static String encryptByPublic(String content) {
        try {
            PublicKey pubkey = getPublicKeyFromX509(ALGORITHM, RSA_PUBLICE);

            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, pubkey);

            byte plaintext[] = content.getBytes("UTF-8");
            byte[] output = cipher.doFinal(plaintext);

            String s = new String(Base64.encode(output, Base64.DEFAULT));

            return s;

        } catch (Exception e) {
            return "error";
        }
    }

    /**
     * 使用公钥解密
     *
     * @param content 密文
     * @param key     商户私钥
     * @return 解密后的字符串
     */
    public static String decryptByPublic(String content) {
        try {
            PublicKey pubkey = getPublicKeyFromX509(ALGORITHM, RSA_PUBLICE);
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, pubkey);
            InputStream ins = new ByteArrayInputStream(Base64.decode(content, Base64.DEFAULT));
            ByteArrayOutputStream writer = new ByteArrayOutputStream();
            byte[] buf = new byte[128];
            int bufl;
            while ((bufl = ins.read(buf)) != -1) {
                byte[] block = null;
                if (buf.length == bufl) {
                    block = buf;
                } else {
                    block = new byte[bufl];
                    for (int i = 0; i < bufl; i++) {
                        block[i] = buf[i];
                    }
                }
                writer.write(cipher.doFinal(block));
            }
            Log.e("url","解密：11111111");
            return new String(writer.toByteArray(), "utf-8");
        } catch (Exception e) {
            Log.e("url","解密：2222222222");
            return null;
        }
    }

}